﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using Interop = Microsoft.Office.Interop;
using DienLib.ReportLib;

namespace DienVu
{
    /// <summary>
    /// Interaction logic for PopUpWellType.xaml
    /// </summary>
    public partial class WellInfo : UserControl
    {
        Configuration g_config;
        Ticket g_ticket;
        CableDrum g_cabledrum;
        Well g_well;
        DateTime g_date;
        JobType g_jobtype;
        ELUnit g_unit;
        string g_unitName;
        private WellInfo(Configuration config)
        {
            InitializeComponent();
            g_config = config;
            cmbTicket.ItemsSource = g_config.Tickets; // Ticket Combobox
            //comboBox3.DisplayMemberPath = "Number";
            cmbJobType.ItemsSource = g_config.JobTypes; // JobType Combobox
            cmbJobType.DisplayMemberPath = "ShortName";
            cmbCableDrum.ItemsSource = g_config.CableDrums; // CableDrum Combobox
            cmbCableDrum.DisplayMemberPath = "DrumSerial";
            cmbWell.ItemsSource = g_config.Wells; // Well Combobox
            cmbWell.DisplayMemberPath = "Name";
        }

        /// <summary>
        /// Additional Method from User to Get Value back from PopUp
        /// </summary>
        /// <returns>String contain ShipTo Number</returns>
        public static void ShowDialog(Configuration config)
        {
            WellInfo popup = new WellInfo(config);
            Window window = new Window();
            window.Content = popup;
            window.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            window.WindowStyle = System.Windows.WindowStyle.None;
            window.AllowsTransparency = true;
            window.Background = System.Windows.Media.Brushes.Transparent;
            window.Topmost = true;
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.MouseLeftButtonDown += Window_MouseLeftButtonDown;
            System.Media.SystemSounds.Beep.Play();
            window.ShowDialog(); // ShowDialog can be used Internal ? HA HA HA ! Any Side Effect ?
            window.MouseLeftButtonDown -= Window_MouseLeftButtonDown;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // MessageBox.Show((comboBox3.SelectedItem as Ticket).ToString());
            // Mot vai thong tin khong tim thay trong Database luc nay can phai hoi lai de confirm
            g_ticket = cmbTicket.SelectedItem as Ticket;
            g_cabledrum = cmbCableDrum.SelectedItem as CableDrum;
            g_well = cmbWell.SelectedItem as Well;
            g_jobtype = cmbJobType.SelectedItem as JobType;
            g_unitName = comboBox4.Text;
            try { g_date = Convert.ToDateTime(textBox1.Text); }
            catch (Exception ex)
            {
                DienLib.PopUp.PopUpOK.ShowDialog("Your Date input is not in the \"Correct Format\" !\r\n" + ex.Message + "\r\nRETRY NOW !", "Error DATE");
                return;
            }
            string farpacName = g_well.Name + "_" + g_date.ToString("ddMMMyy") + "_" + comboBox4.Text.Replace("-", "") + "_" + g_jobtype.ShortName + "_" + "FinalRpt.xlsx";
            string newFarpacPath = g_config[Configuration.Paths.FILE_FARPAC_Sample].Substring(0, g_config[Configuration.Paths.FILE_FARPAC_Sample].LastIndexOf('\\')) + "\\" + farpacName;
            Interop.Excel.Workbook book;
            if (System.IO.File.Exists(newFarpacPath))
            {
                // If File Already Exist
                DienLib.PopUp.PopUpResult res = DienLib.PopUp.PopUpOKCancel.ShowDialog("\"Farpac already exist !\" Do you want to OVERWRITE ?", "FARPAC EXISTED");
                if (res == DienLib.PopUp.PopUpResult.CANCEL)
                {
                    DienLib.OfficeLib.Excel.OpenBookVisible(newFarpacPath); ///////////////////////////////////////////////////////////
                    return;
                } // Existed then Open & return
                else
                    book = DienLib.OfficeLib.Excel.BookOpen(newFarpacPath); //////////////////////////////////////////////////////
            }
            else 
                book = DienLib.OfficeLib.Excel.BookClone(g_config[Configuration.Paths.FILE_FARPAC_Sample], newFarpacPath); /////////////////////////////////////////

            // Ready to Fill/OVERWRITE new FARPAC now
            DienLib.OfficeLib.Excel xls = new DienLib.OfficeLib.Excel();
            xls.InitBook(book, "Master list", true); ///////////////////////////////////////////////
            int row = 8; // TODO: Initialize to an appropriate value
            int column = 2; // TODO: Initialize to an appropriate value
            xls.WriteCell<string>(row = 8, column, g_ticket.Number); //Ticket
            xls.WriteCell<DateTime>(++row, column, g_date); //Date
            xls.WriteCell<string>(++row, column, "BONGKOT");
            xls.WriteCell<string>(++row, column, "GULF OF THAILAND");
            xls.WriteCell<string>(++row, column, "SONGKHLA");
            xls.WriteCell<string>(++row, column, "THAILAND");
            xls.WriteCell<string>(++row, column, g_well.Name);
            xls.WriteCell<string>(++row, column, "PTTEP. PUBLIC COMPANY LTD.");
            xls.WriteCell<string>(++row, column, "BKT-WP-26");
            xls.WriteCell<string>(++row, column, g_unitName);
            xls.WriteCell<string>(++row, column, g_jobtype.FarpacName);

            xls.WriteCell<string>(row = 20, column, "DIEN VU"); // Engineer1
            xls.WriteCell<string>(++row, column, "477410");
            xls.WriteCell<string>(row = 28, column, "SOMSAK J."); // Crew Chief1
            xls.WriteCell<string>(++row, column, "SUBIN N."); // Operator 1
            xls.WriteCell<string>(++row, column, "THANAYUTH S."); // Operator 2
            xls.WriteCell<string>(row = 48, column, "KANTHAD P. / SANIT B."); // Company Man

            xls.WriteCell<string>(row = 54, column, "CH"); // Job Type CH - OH
            xls.WriteCell<string>(++row, column, "DEVIATED");
            xls.WriteCell<double>(++row, column, g_well.DrillDepth); // Drill Depth
            xls.WriteCell<double>(++row, column, g_ticket.JobMD); // Job MD
            xls.WriteCell<double>(++row, column, g_ticket.JobTVD); // Job TVD
            xls.WriteCell<double>(++row, column, g_well.TubingSize); // Casing Size
            xls.WriteCell<double>(++row, column, g_well.TubingShoe); // Casing Depth
            xls.WriteCell<double>(++row, column, g_well.MaxBHT); // Max BHT
            xls.WriteCell<double>(++row, column, g_well.WHP); // Final WHP
            xls.WriteCell<string>(++row, column, g_well.WellFluid); // Well Fluid
            xls.WriteCell<string>(++row, column, g_well.Gravity); // Specific Gravity
            xls.WriteCell<double>(++row, column, g_well.FluidLevel); // Fluid Level
            xls.WriteCell<double>(++row, column, g_well.BitSize); // Bit Size
            xls.WriteCell<double>(++row, column, g_well.MinID); // Min ID
            xls.WriteCell<double>(++row, column, g_well.MaxDEV); // Max Dev
            xls.WriteCell<double>(++row, column, g_well.MaxDEV_Depth); // Depth at Max Dev
            xls.WriteCell<double>(++row, column, g_well.KOP_Depth); // Kick Off Point
            xls.WriteCell<double>(++row, column, g_well.MaxDLR); // Max Dog Leg Rate
            xls.WriteCell<double>(++row, column, g_well.MaxDLR_Depth); // Depth at Max Dog Leg Rate
            xls.WriteCell<double>(++row, column, g_well.DevTD); // Deviation TD

            string desc; DateTime date;
            if (g_jobtype.ShortName == "CBL") { desc = g_well.GammaLogName; date = g_well.GammaLogDate; }
            else { desc = g_well.CCLLogName; date = g_well.CCLLogDate; }
            xls.WriteCell<string>(++row, column, desc); // Correlation Log Description
            xls.WriteCell<DateTime>(++row, column, date); // Coorelation Log Date

            xls.WriteCell<double>(++row, column, g_well.DirTD); // Direction at TD.

            xls.WriteCell<string>(row = 196, column, g_cabledrum.DrumSerial); // Drum Serial
            xls.WriteCell<string>(++row, column, g_cabledrum.CableSerial); // Cable Serial
            xls.WriteCell<string>(++row, column, g_cabledrum.CableType); // Cable Type
            xls.WriteCell<double>(++row, column, g_cabledrum.TotalLength); // StartLength
            //xls.WriteCell<double>(++row, column, g_cabledrum.TotalLength); // Cut Length
            //xls.WriteCell<double>(++row, column, g_cabledrum.TotalLength); // End Length
            xls.WriteCell<int>(row = 202, column, g_cabledrum.TotalRuns); // Previous Run
            //xls.WriteCell<double>(++row, column, g_cabledrum.TotalLength); // Runs this Job
            //xls.WriteCell<int>(++row, column, ); // Total Runs
            book.Application.Visible = true;
            //xls.CloseBook();
            this.close();
        }

        private void close()
        {
            try { Window.GetWindow(this).Close(); }
            catch (Exception ex) { throw new InvalidOperationException("Cannot close Parent not Window : " + ex.Message); }

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //this._result = PopUp.PopUpResult.CANCEL;
            this.close();
        }

        private static void Window_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            (sender as System.Windows.Window).DragMove();
        }

        private void cmbTicket_DropDownClosed(object sender, EventArgs e)
        {   // Cat phan Well Name di
            Ticket ticket = cmbTicket.SelectedItem as Ticket;
            if (ticket == null) return;

            //    comboBox3.Text = ticket.Number;


            cmbWell.SelectedIndex = -1;
            cmbJobType.SelectedIndex = -1;
            textBox1.Text = "";

            #region Change WellName as is
            if (ticket.WellName.Trim() != string.Empty)
            {   // Neu Ticket gan voi WellName thi kiem tra WellName
                foreach (Well well in cmbWell.ItemsSource)
                {   // Neu WellName trung voi ticket.WellName thi Select thang nay
                    if (well.Name.Trim() == ticket.WellName.Trim()) { cmbWell.SelectedItem = well; break; }
                }
            }
            #endregion

            #region Change Selected as is
            if (ticket.JobType.Trim() != string.Empty)
            {
                foreach (JobType jobtype in cmbJobType.ItemsSource)
                {
                    if (ticket.JobType.Trim() == jobtype.ShortName.Trim()) { cmbJobType.SelectedItem = jobtype; break; }
                }
            }
            #endregion

            #region Change Date Time as is
            if (ticket.ClosedDate != DateTime.MinValue) textBox1.Text = ticket.ClosedDate.ToString("dd-MMM-yy");
            #endregion

            #region Change Cable Drum as is
            // Need information from ELUnit
            // Now DUMMY FIRST
            cmbCableDrum.SelectedIndex = 1;
            #endregion
        }


    }
}
